package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.file.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmUserService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zzy
 * @date 2022/7/17 16:48
 */

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {

    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private MinIoTemplate minIoTemplate;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Override
    @Async
    public void autoScanWmNews(Long newsId) throws Exception {
        //入参判空
        if (newsId == null) {
            log.warn("newsId为空");
            return;
        }

        //查询新闻文字
        //查询新闻为空-响应失败
        WmNews wmNews = wmNewsService.getById(newsId);
        if (wmNews == null) {
            log.warn("新闻" + newsId + "为空");
            return;
        }

        //提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);

        //提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imagesList = getImages(images, content);

        //OCR图片提取文字识别 入参是图片 出参是字符串
        String textFromOCR = orcCheck(imagesList);
        text = text + "_" + textFromOCR;

        //使用DFA算法进行自建敏感词处理
        Boolean dfaResult = dfaCheck(text);
        if (!dfaResult) {
            //DFA审核没有提供的话，需要更新文章状态
            updateWmNews(2, "DFA审核没有通过", null, newsId.intValue());
            return;
        }
        //调用敏感词Mapper，查询所有敏感词
        //DFA初始化
        //DFA敏感词匹配
        //判断结果   写一个方法


        //调用文字审核接口
        //审核失败--wmNews修改方法
        //审核不确定--我mNews修改方法
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean textScanResult = checkResult(textScan, null, newsId.intValue());
        if (!textScanResult) {
            log.warn("文字审核失败");
            return;
        }

        //调用图片审核接口
        //审核失败--wmNews修改方法
        //审核不确定--我mNews修改方法
        Map imagesScan = greenImageScan.imageScan(imagesList);
        Boolean imagesScanResult = checkResult(textScan, null, newsId.intValue());
        if (!imagesScanResult) {
            log.warn("图片审核失败");
            return;
        }

        //远程调用ArticleClient保存文章
        ArticleDto dto = WmNews2ArticleDto(wmNews);
        ResponseResult responseResult = articleClient.saveArticle(dto);
        //判断响应结果是不是200
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("文章保存失败");
            return;
        }
        Long articleId = (Long) responseResult.getData();
        //将articleId写到wmNews表中
        updateWmNews(9, "审核通过", articleId, newsId.intValue());

    }

    //ORC图片文字识别  接受图片，提取文字并返回 string images
    private String orcCheck(List<byte[]> images) throws IOException, TesseractException {
        if (CollectionUtils.isEmpty(images)) {
            return "";
        }
        //循环遍历
        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            //调用OCR工具类，提取文字内容
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            BufferedImage read = ImageIO.read(byteArrayInputStream);

            String text = OcrUtil.doOcr(read);

            //将文字内容组合成一个字符中，最终返回
            builder.append("_").append(text);
        }
        return builder.toString();
    }

    //DFA写一个敏感词方法
    private Boolean dfaCheck(String text) {
        if (StringUtils.isEmpty(text)) {
            return true;
        }
        //使用DFA算法进行自建敏感词处理
        //调用敏感词Mapper，查询所有敏感词
        QueryWrapper<WmSensitive> wrapper = new QueryWrapper<>();
        wrapper.select("sensitive");
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return true;
        }

        List<String> words = wmSensitives.stream().filter(Objects::isNull)
                .map(WmSensitive::getSensitives)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(words)) {
            return true;
        }

        //DFA初始化
        SensitiveWordUtil.initMap(words);

        //DFA敏感词匹配
        Map<String, Integer> result = SensitiveWordUtil.matchWords(text);

        //判断结果
        return CollectionUtils.isEmpty(result);
    }

    //提取新闻文字
    public String getText(String title, String content) {
        //提取content里面的文字内容
        if (StringUtils.isBlank(content)) {
            return title;
        }
        List<Map> maps = JSON.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return title;
        }
        StringBuilder builder = new StringBuilder();
        for (Map map : maps) {
            if (CollectionUtils.isEmpty(map)) {
                continue;
            }
            Object type = map.get("type");
            if ("text".equals(type)) {
                String value = (String) map.get("value");
                builder.append(value);
            }
        }
        //将content文字内容进行组合
        builder.append("_").append(title);
        //返回组合后的结果
        return builder.toString();
    }

    //提取新闻图片
    private List<byte[]> getImages(String images, String content) {

        //声明总的图片集合
        List<String> finalList = new ArrayList<>();

        //提取封面图--list《String》
        if (StringUtils.isNoneBlank(images)) {
            String[] split = images.split(",");
            if (ArrayUtils.isNotEmpty(split)) {
                List<String> list = Arrays.asList(split);
                //放入大集合
                finalList.addAll(list);
            }
        }
        //提取内容图--list《String》
        if (StringUtils.isNoneBlank(content)) {
            List<Map> maps = JSON.parseArray(content, Map.class);
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map map : maps) {
                    if (CollectionUtils.isEmpty(map)) {
                        continue;
                    }
                    Object type = map.get("type");
                    if ("images".equals(type)) {
                        String value = (String) map.get("value");
                        //放入大集合
                        finalList.add(value);
                    }
                }
            }
        }
        List<byte[]> result = new ArrayList<>();
        //遍历--list《String》，使用MinioTemplate.download,转成List<byte[]>
        if (CollectionUtils.isEmpty(finalList)) {
            for (String url : finalList) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                byte[] bytes = minIoTemplate.downLoadFile(url);
                result.add(bytes);
            }
        }
        //返回集合
        return result;
    }

    //调用文字审核接口 //调用图片审核接口
    //更新WmNews状态
    private Boolean updateWmNews(Integer status, String reason, Long articleId, Integer newsId) {
        WmNews wmNews = new WmNews();
        wmNews.setId(newsId);
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        if (articleId != null) {
            wmNews.setArticleId(articleId);
        }
        return wmNewsService.updateById(wmNews);
    }

    private Boolean checkResult(Map result, Long articleId, Integer newsId) {
        if (CollectionUtils.isEmpty(result)) {
            log.warn("审核日志为空");
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        if ("pass".equals(suggestion)) {
            return true;
        } else if ("block".equals(suggestion)) {
            //更新WmNews状态
            updateWmNews(2, "未通过", articleId, newsId);
            return false;
        } else if ("review".equals(suggestion)) {
            updateWmNews(3, "转人工审核", articleId, newsId);
            return false;
        }
        return true;
    }

    //远程调用ArticleClient保存文章
    @Autowired
    private WmChannelService wmChannelService;
    @Autowired
    private WmUserService wmUserService;

    public ArticleDto WmNews2ArticleDto(WmNews wmNews) {
        if (wmNews == null) {
            return null;
        }
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);

        dto.setLayout(wmNews.getType());
        //查询渠道的名称
        Integer channelId = wmNews.getChannelId();
        if (channelId != null) {
            WmChannel channel = wmChannelService.getById(channelId);
            if (channel != null) {
                dto.setChannelName(channel.getName());
            }
        }
        //获取作者名
        Integer userId = wmNews.getUserId();
        if (userId != null) {
            dto.setAuthorId(userId.longValue());
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser != null) {
                dto.setAuthorName(wmUser.getName());
            }
        }
        return dto;
    }

    @Autowired
    private IScheduleClient scheduleClient;

//    //消费任务  调用fegin接口
//    @Scheduled(fixedRate = 1000)
//    public void geTask() {
//
//        ResponseResult responseResult = scheduleClient.poll();
//        if (responseResult == null && responseResult.getCode() != 200) {
//            log.warn("消费失败");
//            return;
//        }
//        //执行成功--->Task
//        String data = (String) responseResult.getData();
//        if (StringUtils.isEmpty(data)) {
//            log.warn("没有可消费任务");
//            return;
//        }
//        Task task = JSON.parseObject(data, Task.class);
//        if (task == null) {
//            log.warn("没有可消费任务");
//            return;
//        }
//
//        byte[] parameters = task.getParameters();
//        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
//        if (wmNews == null) {
//            log.warn("参数缺失");
//            return;
//        }
//        try {
//            autoScanWmNews(wmNews.getId().longValue());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

}
